/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author: WJW
 * Date: 2024-08-10
 * Time: 15:53
 */
//单例模式 （饿汉）线程安全
class Singleton{
    private static Singleton instance = new Singleton();
    public static Singleton getInstance(){
        return instance;
    }
    private Singleton(){}
}

//单例模式 （懒汉）线程不安全
//线程安全 执行效率 双重检验锁
class SingletonLazy{
    //volatile 避免指令重排序带来的问题
    private volatile static SingletonLazy instance = null;
    private static Object Locker = new Object();
    public static SingletonLazy getInstance(){
        //双重检验锁。加锁把if和new包裹到一起
        //在锁外头加上条件 首次调用才加锁 后续调用就不必加锁了
        //第一个if是判断是否加锁。第二个if是判断是否要创建对象。
       if(instance == null){
           synchronized (Locker){
               if(instance == null){
                   instance = new SingletonLazy();
               }
           }
       }
       return instance;
    }
    private SingletonLazy(){ }
}
public class ThreadDemo {
    public static void main(String[] args) {

    }
}
